package com.wuyb.exception;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.wuyb.enums.ErrorCode;
import com.wuyb.pojo.entity.BaseResponse;
import com.wuyb.pojo.entity.ResultUtils;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.PrintWriter;

/**
 * 当未登录或者token失效时访问接口时，自定义的返回结果
 *
 * @Author: wyb
 * @Date: 2024/01/08/19:26
 * @Description:
 */
@Component
@Slf4j
public class RestAuthorizeationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        PrintWriter out = response.getWriter();
        log.error(authException.getMessage());
        BaseResponse error = ResultUtils.error(ErrorCode.FORBIDDEN_ERROR.getCode(), "请登录后再访问");
        out.write(new ObjectMapper().writeValueAsString(error));
        out.flush();
        out.close();
    }
}
